package com.tyut.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.tyut.mapper.UserMapper;
import com.tyut.pojo.PageBean;
import com.tyut.pojo.User;
import com.tyut.service.UserService;
import com.tyut.utils.Md5Util;
import com.tyut.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Map;


@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public User findByName(String username) {
        User user = userMapper.findByName(username);
        return user;
    }

    @Override
    public void register(String username, String password) {
        String md5String = Md5Util.getMD5String(password);
        userMapper.add(username, md5String);
    }

    @Override
    public void update(User user) {
        user.setUpdateTime(LocalDateTime.now());
        userMapper.update(user);
    }

    @Override
    public void updateAvatar(String avatarUrl) {
        Map<String, Object> map = ThreadLocalUtil.get();
        User user = new User();
        user.setId((Integer) map.get("id"));
        user.setUserPic(avatarUrl);
        user.setUpdateTime(LocalDateTime.now());
        userMapper.updateAvatar(user);
    }

    @Override
    public void updatePwd(String newPwd) {
        Map<String, Object> map = ThreadLocalUtil.get();
        User user = new User();
        user.setId((Integer) map.get("id"));
        String md5String = Md5Util.getMD5String(newPwd);
        user.setPassword(md5String);
        user.setUpdateTime(LocalDateTime.now());
        userMapper.updatePwd(user);
    }

    @Override
    public void delete(Integer id) {
        userMapper.delete(id);
    }

    @Override
    public PageBean<User> getUser(Integer pageNum, Integer pageSize,String userRole,String username) {
        PageHelper.startPage(pageNum, pageSize);
        Page<User> page = (Page<User>) userMapper.getUser(userRole,username);
        return new PageBean(page.getTotal(), page.getResult());
    }

    @Override
    public void updateState(Integer id, String state) {
        userMapper.updateState(id,state);
    }


}
